package net.controller;


import net.common.Msg;
import net.pojo.User;
import net.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;


@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    UserService userService;

    //用户注册
    @RequestMapping("/regist")
    public String regist(User user){
        int resultCount = userService.register(user);
        return "/client/login.jsp";
    }

    //用户登录
    @RequestMapping("/login")
    public String login(HttpServletRequest request,String username,String password, Model model){
        User user = userService.findByNameAndPass(username,password);
        if (user != null) {
           request.getSession().setAttribute("user",user);
            return "/index.jsp";
        }else {
           model.addAttribute("msg","用户名或者密码错误");
            return "/client/login.jsp";
        }
    }

    //用户退出
    @RequestMapping("/exit")
    public String exit(HttpSession session){
        session.invalidate();
        return "/index.jsp";
    }

    //校对用户是否已经注册
    @RequestMapping("/checkUser")
    @ResponseBody
    public Msg checkUser(User user){
        int resultCount = userService.checkUserName(user.getUsername());
        Msg msg = new Msg();
        if (resultCount==0){
            msg.setFlag(true);
        }else {
            msg.setFlag(false);
        }
        return msg;
    }
}
